package com.qk.management.web;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Objects;

/**
 * @author kaoM1Jy
 * @date 2025/10/11 10:42
 * @description:
 */
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER_NAME = "token";
    @Override
    public void doFilter(ServletRequest req, ServletResponse reps, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) reps;
        String path = request.getRequestURI();
        if(Objects.equals(LOGIN_PATH, path)){
            chain.doFilter(request, response);
            return;
        }
        String token= request.getHeader(TOKEN_HEADER_NAME);
        if(ObjectUtil.isEmpty( token)){
            response.setStatus(401);
            return;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            //TODO 提取用户信息如何处理？
            String username= claims.get("username", String.class);
            Object id = claims.get("id");

            chain.doFilter(request, response);
            return;
        } catch (Exception e) {
            response.setStatus(401);
            return;
        }
    }
}
